<!--
 * @Author: your name
 * @Date: 2020-03-26 09:41:08
 * @LastEditTime: 2020-03-26 09:41:10
 * @LastEditors: Please set LastEditors
 * @Description: 金牛座   -- 已接单成功
 -->

<template>
  <div>
    <van-form class="taurus">
      <!-- 账号 -->
      <van-field
        v-model="ruleForm.account"
        type="tel"
        maxlength="11"
        label="账号"
        placeholder="请填写账号"
        clearable
      />
      <!-- 密码 -->
      <van-field
        v-model="ruleForm.password"
        type="password"
        label="密码"
        placeholder="请填写密码"
        clearable
      />
      <!-- 任务类型 -->
      <van-field v-model="IntervalTime" type="tel" label="抢单间隔(s)" placeholder="请填写抢单间隔" clearable />
      <van-field name="radio" label="任务类型">
        <template #input>
          <van-checkbox-group v-model="result" direction="horizontal">
            <van-checkbox
              v-for="(option, index) in typeOptions"
              :key="index"
              :name="option.name"
              checked-color="#e4393c"
              shape="square"
            >{{ option.label }}</van-checkbox>
          </van-checkbox-group>
        </template>
      </van-field>
      <!-- 提示 -->
      <van-cell-group>
        <van-cell
          class="van-cell__tip"
          v-for="(content, index) in returnContent"
          :key="index"
          :title="content"
        />
      </van-cell-group>
    </van-form>
    <!-- 按钮 -->
    <div class="popup-open__btn">
      <van-button type="warning">做单</van-button>
      <van-button type="danger" @click="onStart">{{ startFlag ? '停止接单' : '开始接单' }}</van-button>
    </div>

    <van-dialog v-model="show" title="开启账号" :showConfirmButton="false" :showCancelButton="false">
      <van-cell v-for="(bind, index) in bindInfo" :key="index" center :title="bind.bindAccountName">
        <template #right-icon>
          <van-switch
            v-model="bind.note"
            active-color="#e4393c"
            size="24"
            @change="onChange(bind.accountId)"
          />
        </template>
      </van-cell>
    </van-dialog>
  </div>
</template>

<script>
import dayjs from "dayjs";
import * as taurus from "@/api/taurus";
import { alertMsg, saveInfo, audio } from "@/utils/index";
export default {
  name: "Taurus",
  props: {
    index: {
      type: String,
      default: ""
    },
    item: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  data() {
    return {
      // 参数
      ruleForm: {
        account: "17717751808",
        password: "Zz930329"
      },
      // 循环时间
      IntervalTime: 30,
      // 任务类型
      result: ["3", "2"],
      typeOptions: [
        {
          label: "不接货返",
          name: "3"
        },
        {
          label: "不接浏览",
          name: "2"
        }
      ],
      // 开始登陆 标记
      startFlag: false,
      // 定时器
      timer: null,
      // 任务ID
      taskId: "",
      // 接口返回提示
      returnContent: [],
      // 已有平台
      iconItems: [],
      // 请求头
      headers: "",
      token: "",
      userId: "",
      show: false,
      bindInfo: [],
      // 已接单标记
      isAcceptSuc: false,
      activeIndex: ""
    };
  },
  watch: {
    // 监听接单状态
    startFlag() {
      if (this.item.index === 35 && this.index !== "") {
        this.$emit("changeOpened", {
          index: this.index,
          status: this.isAcceptSuc
            ? "已接单"
            : this.startFlag
            ? "已启动"
            : "待启动",
          startFlag: this.startFlag,
          content: this.returnContent
        });
      }
    },
    // 监听提示
    returnContent() {
      if (this.returnContent.length >= 10) {
        this.returnContent = this.returnContent.filter((item, i) => i < 5);
      }
    },
    // 监听当前索引
    index() {
      if (this.item.index === 35 && this.index !== "") {
        this.activeIndex = this.index;
        // 获取保存账号信息
        this.ruleForm.account = this.item.user;
        this.ruleForm.password = this.item.pass;
        this.result = this.item.type || ["3", "2"];

        // 如为 已接单 => 改变状态
        if (this.item.opened === "已接单") {
          this.$emit("changeOpened", {
            index: this.index,

            status: "待启动",
            startFlag: this.startFlag,
            content: this.returnContent
          });
        }
      }
    }
  },
  created() {
    if (this.item.index === 35 && this.index !== "") {
      this.activeIndex = this.index;
      // 获取保存账号信息
      this.ruleForm.account = this.item.user;
      this.ruleForm.password = this.item.pass;
      this.result = this.item.type || ["3", "2"];
    }
  },
  methods: {
    // 开始接单
    onStart() {
      this.onLogin();
    },
    // 登录
    onLogin() {
      const _this = this;
      this.returnContent = [];
      if (!this.startFlag) {
        this.headers = "";
        this.startFlag = true;
        // 登录提示
        this.returnContent.unshift(alertMsg("正在登录"));
        // 异步登录
        let param = {
          type: "post",
          headers: "",
          data: {
            account: this.ruleForm.account,
            password: this.ruleForm.password,
            token: "-",
            version: "20200303",
            _time: dayjs().valueOf(),
            terminal: 2,
            terminalSerial: "-"
          }
        };
        taurus.ajaxFun(taurus.getLogin, param, res => {
          _this.returnContent.unshift(alertMsg(res.msg));
          if (res.code === 0) {
            // 登录成功  => 保存账号信息
            saveInfo({
              user: _this.ruleForm.account,
              pass: _this.ruleForm.password,
              type: _this.result,
              index: _this.index
            });
            _this.userId = res.data.userId;
            _this.token = res.data.token;
            // 获取账户
            _this.onGetBindInfo(_this);
          } else {
            _this.startFlag = false;
          }
        });
      } else {
        this.returnContent.unshift(alertMsg("接单取消"));
        clearInterval(_this.timer);
        this.startFlag = false;
        this.isAcceptSuc = false;
        this.$toast({ message: "已停止接单" });
      }
    },
    // 获取账户
    onGetBindInfo(_this) {
      _this.returnContent.unshift(alertMsg("获取接单账号..."));
      let param = {
        type: "post",
        headers: "",
        data: {
          token: _this.token,
          version: "20200303",
          _time: dayjs().valueOf(),
          terminal: 2,
          terminalSerial: "-"
        }
      };
      taurus.ajaxFun(taurus.getBindInfo, param, res => {
        _this.returnContent.unshift(alertMsg(res.msg));
        if (res.code === 0) {
          // 弹窗 选择账户
          this.bindInfo = res.data;
          this.show = true;
        } else {
          _this.startFlag = false;
        }
      });
    },
    // 开启账号
    onChange(accountId) {
      this.show = false;
      this.onGetAllocation(this, accountId);
    },
    // 任务列表
    onGetAllocation(_this, accountId) {
      clearInterval(_this.timer);
      _this.returnContent.unshift(alertMsg("正在努力为您接单..."));
      let param = {
        type: "post",
        data: {
          terminalSerial: "-",
          _time: dayjs().valueOf(),
          terminal: 2,
          version: "20200303",
          accountId: accountId,
          token: _this.token
        }
      };
      taurus.ajaxFun(taurus.getAllocation, param, res => {
        if (res.code === 0) {
          if (res.data) {
            let index = _this.result.findIndex(
              item => item == res.data.taskCategory
            );
            if (index === -1) {
              _this.returnContent.unshift(alertMsg("接单成功，请前往做单..."));
              audio();
              _this.isAcceptSuc = true;
              _this.startFlag = false;
              _this.$emit("changeOpened", {
                index: _this.activeIndex,
                status: "已接单",
                startFlag: false,
                content: ["接单成功，请前往做单..."]
              });
            } else {
              _this.returnContent.unshift(alertMsg("浏览单不接，跳过..."));
              _this.timer = setInterval(() => {
                if (_this.startFlag) {
                  _this.onGetAllocation(_this, accountId);
                }
              }, _this.IntervalTime * 1000);
            }
          } else {
            _this.timer = setInterval(() => {
              if (_this.startFlag) {
                _this.onGetAllocation(_this, accountId);
              }
            }, _this.IntervalTime * 1000);
          }
        } else {
          _this.returnContent.unshift(alertMsg(res.msg));
          _this.startFlag = false;
          if (res.msg === "您有未完成的订单，先完成在接单") {
            _this.returnContent.unshift(alertMsg("接单成功，请前往做单..."));
            audio();
            _this.isAcceptSuc = true;
            _this.startFlag = false;
            _this.$emit("changeOpened", {
              index: _this.activeIndex,
              status: "已接单",
              startFlag: false,
              content: ["接单成功，请前往做单..."]
            });
          }
        }
      });
    }
    // 取消订单
    // onCancelOrder() {
    //   clearInterval(_this.timer);
    //   _this.returnContent.unshift(alertMsg("浏览单不接，跳过..."));
    //   let param = {
    //     type: "post",
    //     data: {
    //       cancelReason: 2,
    //       _time: dayjs().valueOf(),
    //       terminal: 2,
    //       version: "20200303",
    //       accountId: accountId,
    //       token: _this.token,
    //       terminalSerial: "-",
    //       orderSign: ''
    //     }
    //   };
    //   taurus.ajaxFun(taurus.getAllocation, param, res => {
    //     if (res.code === 0) {
    //       if (res.data) {
    //         let index = _this.result.findIndex(item => item == res.data.taskCategory);
    //         if (index === -1) {
    //           _this.returnContent.unshift(alertMsg("接单成功，请前往做单..."));
    //           audio();
    //           _this.isAcceptSuc = true;
    //           _this.startFlag = false;
    //           _this.$emit("changeOpened", {
    //             index: _this.activeIndex,
    //             status: "已接单",
    //             startFlag: false,
    //             content: ["接单成功，请前往做单..."]
    //           });
    //         } else {

    //         }
    //       } else {
    //         _this.timer = setInterval(() => {
    //           if (_this.startFlag) {
    //             _this.onGetAllocation(_this, accountId);
    //           }
    //         }, _this.IntervalTime * 1000);
    //       }
    //     } else {
    //       _this.returnContent.unshift(alertMsg(res.msg));
    //       _this.startFlag = false
    //     }
    //   });
    // }
  }
};
</script>

<style lang="scss" scoped>
.popup-open__form-code {
  width: 100%;
  @include flex($flexWrap: nowrap);
  .van-image {
    flex: 0 0 100px;
    height: 44px;
  }
}
</style>